//
//  UIButton+location.m
//  voiceguide
//
//  Created by 陈曦 on 14-6-11.
//  Copyright (c) 2014年 mafengwo. All rights reserved.
//

#import "UIButton+location.h"
#import "Utils_Swizzing.h"


static const char titleViewCenterKey;
static const char imageViewCenterKey;

static CGRect (*oldTitle)(UIButton *self,SEL _cmd, CGRect contentRect);
static CGRect (*oldImage)(UIButton *self,SEL _cmd, CGRect contentRect);


static CGRect rectWithPointAndRect(CGRect rect ,CGPoint p)
{
    rect.origin.x = p.x - rect.size.width / 2;
    rect.origin.y = p.y - rect.size.height / 2;
    return rect;
}


static CGRect newTitle(UIButton *self,SEL _cmd, CGRect contentRect)
{
    CGRect rect = objc_runOldMethod([UIButton class],oldTitle,self,_cmd,contentRect);
    NSValue *v = [self getAssociativeValue:&titleViewCenterKey];
    if (v)
    {
        CGPoint p = v.CGPointValue;
        rect = rectWithPointAndRect(rect, p);
    }
    return rect;
}
static CGRect newImage(UIButton *self,SEL _cmd, CGRect contentRect)
{
    CGRect rect = objc_runOldMethod([UIButton class],oldImage,self,_cmd,contentRect);
    NSValue *v = [self getAssociativeValue:&imageViewCenterKey];
    if (v)
    {
        CGPoint p = v.CGPointValue;
        rect = rectWithPointAndRect(rect, p);
    }
    return rect;
}

@implementation UIButton(location)

+ (void)load
{
    oldTitle = objc_changeMethod(self, @selector(titleRectForContentRect:), newTitle);
    oldImage = objc_changeMethod(self, @selector(imageRectForContentRect:), newImage);
}

- (void)setTitleViewCenter:(CGPoint)titleViewCenter
{
    
    NSValue *v = [NSValue valueWithCGPoint:titleViewCenter];
    [self setRetainNonatomicProperty:v byKey:&titleViewCenterKey];
}

- (CGPoint)titleViewCenter
{
    NSValue *v = [self getAssociativeValue:&titleViewCenterKey];
    return v.CGPointValue;
}


- (void)setImageViewCenter:(CGPoint)imageViewCenter
{
    NSValue *v= [NSValue valueWithCGPoint:imageViewCenter];
    [self setRetainNonatomicProperty:v byKey:&imageViewCenterKey];
}

- (CGPoint)imageViewCenter
{
    NSValue *v = [self getAssociativeValue:&imageViewCenterKey];
    return v.CGPointValue;
}

@end
